package com.ytktt.study.week11.task10;

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 全局 ID 生成
 *
 * @author ytk
 */
@Slf4j
public class GlobalIdApplication {

    private static volatile GlobalIdApplication singleton;
    private final RedisClient redisClient;
    private GlobalIdApplication() {
        this.redisClient = RedisClient.create("redis://localhost:6379/0");
    }
    public static GlobalIdApplication getInstance() {
        if (singleton == null) {
            synchronized (GlobalIdApplication.class) {
                if (singleton == null) {
                    singleton = new GlobalIdApplication();
                }
            }
        }
        return singleton;
    }

    public String getNextId(String prefix) {
        StatefulRedisConnection<String, String> connection = this.redisClient.connect();
        RedisCommands<String, String> syncCommands = connection.sync();
        Long incr = syncCommands.incr(prefix);
        connection.close();
        return prefix + incr;
    }

    public void closeRedis() {
        this.redisClient.shutdown();
    }

    public static void main(String[] args) throws InterruptedException {
        GlobalIdApplication application = GlobalIdApplication.getInstance();
        ExecutorService executorService = Executors.newFixedThreadPool(8);
        for (int i = 0; i < 100; i++) {
            executorService.submit(() -> {
                log.info("thread: {} get: {}", Thread.currentThread().getName(), application.getNextId("global-id"));
            });
        }
        Thread.sleep(2_000);
        executorService.shutdown();
        application.closeRedis();
    }
}
